package com.uzai.console.web.sys;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import com.uzai.common.enums.IdentityEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.annotation.SystemLogType;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.dto.sys.datahandle.*;
import com.uzai.console.entity.ConfigPlan;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.UserType;
import com.uzai.console.enums.OperationTypeEnum;
import com.uzai.console.enums.SystemModelEnum;
import com.uzai.console.mapper.ConfigPlanMapper;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.mapper.RedPacketMapper;
import com.uzai.console.mapper.UserTypeMapper;
import com.uzai.console.service.sys.DataHandleService;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author mingyang.chen create in 2022/9/29 15:31
 */
@RestController
@RequestMapping(value = "/system/setting")
@Api(value = "系统设置-数据处理", tags = "系统设置")
@Slf4j
public class DataHandleController extends BaseController {


    @Autowired
    private DataHandleService dataHandleService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "提现记录清理", response = Boolean.class)
    @PostMapping("/withdraw/record/clean")
    @SystemLogType(model = SystemModelEnum.WithdrawRecordClean, type = OperationTypeEnum.UPDATE)
    public Object withdrawRecordClean(@RequestBody WithdrawRecordCleanDto withdrawRecordCleanDto) {

        boolean result = dataHandleService.withdrawRecordClean(withdrawRecordCleanDto);
        log.info("withdrawRecordClean result is: {}", result);
        return result;
    }

    @ApiOperation(value = "历史提现记录处理", response = Boolean.class)
    @PostMapping("/withdraw/record/deal")
    @SystemLogType(model = SystemModelEnum.WithdrawRecordClean, type = OperationTypeEnum.UPDATE)
    public Object withdrawRecordDeal(@RequestBody WithdrawRecordDealDto withdrawRecordDealDto) {
        if (Objects.isNull(withdrawRecordDealDto)
                || Objects.isNull(withdrawRecordDealDto.getStartTime()) || Objects.isNull(withdrawRecordDealDto.getEndTime())
                || Objects.isNull(withdrawRecordDealDto.getStatusOld()) || Objects.isNull(withdrawRecordDealDto.getStatusNew())
        ) {
            throw new BusinessException("历史提现记录处理请求参数错误");
        }

        boolean result = dataHandleService.withdrawRecordDeal(withdrawRecordDealDto);
        log.info("withdrawRecordDeal result is: {}", result);
        return result;
    }

    @ApiOperation(value = "回复语关键词替换", notes = "对所有回复语的关键字进行替换", response = Boolean.class)
    @PostMapping("/keyword/replace")
    @SystemLogType(model = SystemModelEnum.KeywordReplace, type = OperationTypeEnum.UPDATE)
    public Object keywordReplace(@RequestBody KeyWordsReplaceDto keyWordsReplaceDto) {
        if (Objects.isNull(keyWordsReplaceDto) || StringUtils.isAnyBlank(keyWordsReplaceDto.getSourceKeyWord())) {
            throw new BusinessException("关键词替换请求参数错误");
        }
        if (StringUtils.isBlank(keyWordsReplaceDto.getTargetKeyWord())) {
            keyWordsReplaceDto.setTargetKeyWord("");
        }
        boolean result = dataHandleService.keywordReplace(keyWordsReplaceDto);
        log.info("keywordReplace result is: {}", result);
        return result;
    }

    @ApiOperation(value = "智能回复回复语关键词替换", notes = "智能回复回复语关键词替换", response = Boolean.class)
    @PostMapping("/faqReplay/keyword/replace")
    @SystemLogType(model = SystemModelEnum.FaqReplykeywordReplace, type = OperationTypeEnum.UPDATE)
    public Object faqReplayKeywordReplace(@RequestBody KeyWordsReplaceDto keyWordsReplaceDto) {
        if (Objects.isNull(keyWordsReplaceDto) || StringUtils.isAnyBlank(keyWordsReplaceDto.getSourceKeyWord())) {
            throw new BusinessException("智能回复语关键词替换请求参数错误");
        }
        if (StringUtils.isBlank(keyWordsReplaceDto.getTargetKeyWord())) {
            keyWordsReplaceDto.setTargetKeyWord("");
        }
        boolean result = dataHandleService.faqReplyKeywordReplace(keyWordsReplaceDto);
        log.info("faqReplayKeywordReplace result is: {}", result);
        return result;
    }


    @ApiOperation(value = "添加自动订单状态清理配置", response = Boolean.class)
    @PostMapping("/orderStatusCleanConfig/add")
    public Object autoCleanOrderStatus(@RequestBody AutoCleanOrderStatusDto params) {

        if (Objects.isNull(params) || StringUtils.isBlank(params.getConfigJson())) {
            throw new BusinessException("自动清理订单状态请求参数错误");
        }

        boolean result = dataHandleService.addAutoCleanOrderStatusConfig(params);
        log.info("autoCleanOrderStatus result is: {}", result);
        return result;
    }

    @ApiOperation(value = "获取自动订单状态清理配置", response = JSONArray.class)
    @PostMapping("/orderStatusCleanConfig/get")
    public Object getAutoCleanOrderStatusConfig() {

        LoginVo loginInfo = getLoginInfo();

        Object result = dataHandleService.getAutoCleanOrderStatusConfig(loginInfo.getMerId());
        log.info("getAutoCleanOrderStatusConfig result is: {}", result);
        return result;
    }

    @ApiOperation(value = "订单状态清理", response = Boolean.class)
    @PostMapping("/cleanOrderStatus")
    @SystemLogType(model = SystemModelEnum.CleanOrderStatus, type = OperationTypeEnum.UPDATE)
    public Object cleanOrderStatus(@RequestBody CleanOrderStatusDto params) {

        if (Objects.isNull(params) || Objects.isNull(params.getType()) || Objects.isNull(params.getStatus())
            || Objects.isNull(params.getStartTime()) || Objects.isNull(params.getEndTime()) || Objects.isNull(params.getSettle())
        ) {
            throw new BusinessException("订单状态清理请求参数错误");
        }
        List<Integer> validStatus = Lists.newArrayList(1, 2);
        if (!validStatus.contains(params.getStatus())) {
            throw new BusinessException("订单状态清理状态请求参数错误");
        }

        //测试服方便测试，抛弃限流
        if(params.getMerId() != 1547482020152213506L) {
            String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.DATA_HANDLE_ORDER, params.getMerId()));
            if (StringUtils.isNotBlank(val)){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"10分钟只允许一次请求");
            }
        }

        dataHandleService.cleanOrderStatus(params);

        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.DATA_HANDLE_ORDER,params.getMerId()),params.getMerId()+"",10, TimeUnit.MINUTES);

        return true;
    }

    @ApiOperation(value = "用户数据合并", response = Boolean.class)
    @PostMapping("/userData/merge")
    @SystemLogType(model = SystemModelEnum.UserDateMerge, type = OperationTypeEnum.UPDATE)
    public Object userDateMerge(@RequestBody UserDataMergeDto userDataMergeDto) {

        if (Objects.isNull(userDataMergeDto) || Objects.isNull(userDataMergeDto.getUserIdOld()) || Objects.isNull(userDataMergeDto.getUserIdNew())) {
            throw new BusinessException("用户数据合并请求参数错误");
        }
        dataHandleService.userDataMerge(userDataMergeDto);

        return true;
    }

    @ApiOperation(value = "机器人数据迁移", response = Boolean.class)
    @PostMapping("/deviceDate/transfer")
    @SystemLogType(model = SystemModelEnum.DeviceDateTransfer, type = OperationTypeEnum.UPDATE)
    public Object deviceDateTransfer(@RequestBody DeviceDataTranferDto deviceDataTranferDto) {

        if (Objects.isNull(deviceDataTranferDto) || Objects.isNull(deviceDataTranferDto.getDeviceUniqueIdOld()) || Objects.isNull(deviceDataTranferDto.getDeviceUniqueIdNew())) {
            throw new BusinessException("机器人数据数据迁移请求参数错误");
        }

        Long merId = deviceDataTranferDto.getMerId();
        Long deviceUniqueIdOld = deviceDataTranferDto.getDeviceUniqueIdOld();
        Long deviceUniqueIdNew = deviceDataTranferDto.getDeviceUniqueIdNew();

        if(deviceUniqueIdOld.longValue() == deviceUniqueIdNew.longValue()){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "旧机器人和新机器人不能是同一个");
        }

        DeviceWechatInfo deviceWechatInfoNew = deviceWechatInfoMapper.selectById(deviceUniqueIdNew, merId);
        if(deviceWechatInfoNew == null){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人不存在");
        }

        ConfigPlan configPlan_new = configPlanMapper.selectById(deviceWechatInfoNew.getConfigId(), merId);
        if(configPlan_new == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案不存在");
        }

        Long userTypeGroupId = configPlan_new.getUserTypeGroupId();
        if(userTypeGroupId == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案未配置会员类型组信息");
        }

        //买家会员类型
        UserType userType_buyer = userTypeMapper.selectDefault(merId, userTypeGroupId, IdentityEnum.BUYER.getId());
        if(userType_buyer == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案配置会员类型组未包含默认的买家身份会员类型");
        }
        //代理会员类型
        UserType userType_agent = userTypeMapper.selectDefault(merId, userTypeGroupId, IdentityEnum.AGENT.getId());
        if(userType_agent == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案配置会员类型组未包含默认的代理身份会员类型");
        }
        //合伙人会员类型
        UserType userType_partner = userTypeMapper.selectDefault(merId, userTypeGroupId, IdentityEnum.PARTNER.getId());
        if(userType_partner == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新机器人配置方案配置会员类型组未包含默认的合伙人身份会员类型");
        }

        dataHandleService.deviceDateTransfer(deviceDataTranferDto);

        return true;
    }

    @ApiOperation(value = "用户数据处理-修改用户自定义标签", response = Boolean.class)
    @PostMapping("/userData/handerTags")
    @SystemLogType(model = SystemModelEnum.UserTagsHander, type = OperationTypeEnum.UPDATE)
    public Object userTagsHander(@RequestBody UserTagsHanderDto userTagsHanderDto) {
        dataHandleService.userTagsHander(userTagsHanderDto);
        return true;
    }

    @ApiOperation(value = "用户数据处理-修改用户余额", response = Boolean.class)
    @PostMapping("/userData/handerBalance")
    @SystemLogType(model = SystemModelEnum.UserBalanceHander, type = OperationTypeEnum.UPDATE)
    public Object userBalanceHander(@RequestBody UserBalanceHanderDto userBalanceHanderDto) {
        dataHandleService.userBalanceHander(userBalanceHanderDto);
        return true;
    }

    @ApiOperation(value = "历史数据处理-订单记录清理", response = Boolean.class)
    @PostMapping("/dataHandle/order/chean")
    @SystemLogType(model = SystemModelEnum.OrderDelete, type = OperationTypeEnum.DELETE)
    public Object orderClean(@RequestBody HistoryOrderHanderDto historyOrderHanderDto) {
        dataHandleService.orderClean(historyOrderHanderDto);
        return true;
    }
}
